<template>
  <el-breadcrumb
      class="app-breadcrumb"
      :separator-icon="ArrowRight"
  >
    <transition-group name="breadcrumb">
      <el-breadcrumb-item
          v-for="(item, index) in breadcrumbs"
          :key="item.path"
      >
        <span
            v-if="item.redirect === 'noredirect' || index === breadcrumbs.length-1"
            class="no-redirect"
            v-text="item.meta.title"/>
        <a
            v-else
            @click.prevent="handleLink(item)"
            v-text="item.meta.title"
        />
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import {defineComponent, onBeforeMount, watch, reactive, toRefs} from 'vue'
import { ArrowRight } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'

export default defineComponent({
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      breadcrumbs: route.matched,
      handleLink: (item) => {
        const {redirect, path} = item
        if (redirect) {
          router.push(redirect).catch((err) => {
            console.warn(err)
          })
        }
      },
      getBreadcrumb: () => {
        let matched = route.matched.filter((item) => item.meta && item.meta.title)
        const first = matched[0]
        if (!state.isDashboard(first)) {
          matched = [{ path: '/dashboard', meta: { title: '首页' } } ].concat(matched)
        }
        state.breadcrumbs = matched.filter((item) => {
          return item.meta && item.meta.title && item.meta.breadcrumb !== false
        })
      },
      isDashboard: (route) => {
        const name = route && route.name
        if (!name) {
          return false
        }
        return name.toString().trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
      }
    })
    watch(() => route.path, (path) => {
      if (path.startsWith('/redirect/')) {
        return
      }
      state.getBreadcrumb()
    })

    onBeforeMount(() => {
      state.getBreadcrumb()
    })
    
    return {
      ArrowRight,
      ...toRefs(state)
    }
  }
})



</script>


<style lang="scss" scoped>
.el-breadcrumb__inner,
.el-breadcrumb__inner a {
  font-weight: 400 !important;
}

.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
